package org.jimmy.mqtt.controller;

/**
 * @author create by jimmy 2116398125@qq.com
 * @package org.jimmy.mqtt.controller
 * @date 2024/8/14 20:33
 */
import org.jimmy.mqtt.client.EmqMqttClient;
import org.jimmy.mqtt.enums.QoSEnum;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import jakarta.annotation.Resource;
import java.net.URLDecoder;

/**
 * 消息发布控制器
 * @date 2024/8/16 10:06
 * @author create by jimmy 2116398125@qq.com
 */
@Controller
public class PublishController {
    @Resource
    private EmqMqttClient client;

    @Value("${spring.mqtt.client-id}")
    private String clientId;

    @RequestMapping("/pub/connect")
    @ResponseBody
    public String connect() {
        client.connect();
        return clientId + "连接到服务器";
    }

    @RequestMapping("/pub/disConnect")
    @ResponseBody
    public String disConnect() {
        client.disConnect();
        return clientId + "已断开连接";
    }

    @GetMapping("/sendMessage")
    @ResponseBody
    public String sendMessage(@RequestParam("topic") String topic, @RequestParam("message") String message, @RequestParam("qos") QoSEnum qos, @RequestParam("retained") boolean retained) {
        try {
            client.publish(topic, message, qos, retained);
            return "发送成功";
        } catch (Exception e) {
            e.printStackTrace();
            return "发送失败";
        }
    }

    @GetMapping("/pub/subscribe")
    @ResponseBody
    public String subscribe(@RequestParam("topic") String topic, @RequestParam("qos") QoSEnum qos) {
        topic = URLDecoder.decode(topic);
        System.out.println("topic:" + topic);
        client.subscribe(topic, qos);
        return clientId + "已订阅Topic:" + topic + " QoS: " + qos.getCode();
    }
}
